﻿Imports System.Windows.Markup
Imports System.ComponentModel

Namespace OfflineLibrary_WPF
	'http://stackoverflow.com/a/4398752/271351
	Public Class EnumerationExtension
		Inherits MarkupExtension
		Private _enumType As Type


		Public Sub New(enumType__1 As Type)
			If enumType__1 Is Nothing Then
				Throw New ArgumentNullException("enumType")
			End If

			EnumType = enumType__1
		End Sub

		Public Property EnumType() As Type
			Get
				Return _enumType
			End Get
			Private Set(value As Type)
				If _enumType = value Then
					Return
				End If

				Dim enumType__1 = If(Nullable.GetUnderlyingType(value), value)

				If enumType__1.IsEnum = False Then
					Throw New ArgumentException("Type must be an Enum.")
				End If

				_enumType = value
			End Set
		End Property

		Public Overrides Function ProvideValue(serviceProvider As IServiceProvider) As Object
			Dim enumValues = [Enum].GetValues(EnumType)

			Return (From enumValue In enumValues Select New EnumerationMember() With {
			  .Value = enumValue,
			  .Description = GetDescription(enumValue)
			}).ToArray()
		End Function

		Private Function GetDescription(enumValue As Object) As String
			Dim descriptionAttribute = TryCast(EnumType.GetField(enumValue.ToString()).GetCustomAttributes(GetType(DescriptionAttribute), False).FirstOrDefault(), DescriptionAttribute)


			Return If(descriptionAttribute IsNot Nothing, descriptionAttribute.Description, enumValue.ToString())
		End Function

		Public Class EnumerationMember
			Public Property Description() As String
				Get
					Return m_Description
				End Get
				Set(value As String)
					m_Description = value
				End Set
			End Property
			Private m_Description As String
			Public Property Value() As Object
				Get
					Return m_Value
				End Get
				Set(value As Object)
					m_Value = value
				End Set
			End Property
			Private m_Value As Object
		End Class
	End Class
End Namespace
